package com.modules.content.service.Impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.response.ResponseVO;
import com.common.utils.Query;
import com.common.exception.RRException;
import com.common.utils.R;
import com.modules.content.entity.Contents;
import com.modules.content.VO.ContentsVO;
import com.modules.content.mapper.ContentsMapper;
import com.modules.content.service.IContentsService;
import com.modules.contentImages.entity.ContentImages;
import com.modules.contentImages.mapper.ContentImagesMapper;
import com.modules.system.entity.Admin;
import com.modules.system.mapper.AdminMapper;
import com.modules.user.entity.UserEntity;
import com.modules.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service("contentsService")
public class ContentsServiceImpl extends ServiceImpl<ContentsMapper, Contents> implements IContentsService {

    @Autowired
    private ContentsMapper contentsMapper;
    @Autowired
    private ContentImagesMapper contentImagesMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public R getPageList(Map<String, Object> params) {
        IPage<ContentsVO> page = new Query<ContentsVO>().getPage(params);
        List<ContentsVO> list = contentsMapper.getPageList(page);
        if (!list.isEmpty()){
            for (ContentsVO contentsVO: list){
                List<ContentImages> contentImagesList = contentImagesMapper.selectList(new QueryWrapper<ContentImages>().lambda()
                .eq(ContentImages::getContentid, contentsVO.getId())
                .orderByAsc(ContentImages::getSort));
                if (contentImagesList.isEmpty()){
                    contentsVO.setImageNum(0);
                } else {
                    contentsVO.setImageNum(contentImagesList.size());
                }
                contentsVO.setContentImages(contentImagesList);
            }
        }
        page.setRecords(list);
        return R.ok().put("data",page);
    }

    @Override
    public R saveEntity(ContentsVO content, Integer adminId) {
        UserEntity userEntity = userMapper.selectById(adminId);
        if (userEntity == null){
            throw new RRException("管理员不存在");
        }
        if (content.getId() == null){
            content.setCreateTime(new Date());
        } else {
            content.setUpdateUser(adminId);
        }
        // 先保存贴图信息，会得到id
        this.saveOrUpdate(content);

        // 前端传来的图片id集合
        Set<Integer> newContentImgIdSet = new HashSet<>();
        // 原有的图片id集合
        Set<Integer> oldContentImgIdSet = new HashSet<>();
        // 要删除原有的图片id集合
        Set<Integer> delOldContentImgIdSet = new HashSet<>();
        // 要添加原有的图片id集合
        Set<Integer> addOldContentImgIdSet = new HashSet<>();
        List<ContentImages> contentImagesList = contentImagesMapper.selectList(new QueryWrapper<ContentImages>().lambda()
                .eq(ContentImages::getContentid, content.getId()));
        oldContentImgIdSet = contentImagesList.stream().map(ContentImages::getId).collect(Collectors.toSet());
        if (CollUtil.isNotEmpty(content.getImages())){
            for (int i = 0; i< content.getImages().size(); i++){
                ContentImages contentImage = new ContentImages();
                contentImage.setContentid(content.getId());
                if (content.getImages().get(i).indexOf("_") != -1){
                    String[] arr = content.getImages().get(i).split("\\+\\+__");
                    contentImage.setFilepath(arr[0]);
                    contentImage.setId(Integer.parseInt(arr[1]));
                    newContentImgIdSet.add(Integer.parseInt(arr[1]));
                } else {
                    contentImage.setFilepath(content.getImages().get(i));
                    contentImage.setCreateTime(new Date());
                }
                contentImage.setSort(i+1);
                if (contentImage.getId() != null){
                    contentImagesMapper.updateById(contentImage);
                } else {
                    contentImagesMapper.insert(contentImage);
                }
            }
        }
        // 找出前端删除的图片并删除
        for (Integer id: oldContentImgIdSet){
            if (!newContentImgIdSet.contains(id)){
                contentImagesMapper.deleteById(id);
            }
        }

        return R.ok().put("data", content);
    }
}
